import requests
import tkinter as tk
from tkinter import messagebox
import time
import re
from matplotlib import pyplot as plt
import psutil


#测试socks5是否代理成功
def get_real_ip():
    url_test_socks5 = "http://icanhazip.com/"
    while True:
        try:
            req_real = requests.get(url=url_test_socks5,timeout=1).text.replace('\n','')
            newsbox1.insert(0, req_real)
            break
        except:
            messagebox.showinfo(title="提示",message="获取失败，正在重新获取....")

def get_socoks_ip():
    url_test_socks5 = "http://icanhazip.com/"
    proxy = {"http":"socks5://127.0.0.1:30025"}
    try:
        req_sock = requests.get(url=url_test_socks5, proxies=proxy,timeout=1).text.replace('\n', '')
        newsbox2.insert(0, req_sock)
        time.sleep(1)
        if req_sock != newsbox1.get(0.0,'end'):
            messagebox.showinfo(title="提示",message="代理成功！")
        else:
            messagebox.showinfo(title="提示", message="代理失败！")
    except:
        messagebox.showinfo(title="提示", message="获取失败，正在重新获取....")

def get_elapsed_http():
    #测试的地址 -- bilibili官网
    url = "https://www.bilibili.com/"
    sum=0
    #设置请求头部
    headers={
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding':'gzip, deflate, br',
        'Accept-Language':'zh-CN,zh;q=0.9',
        'Cache-Control':'max-age=0',
        'Connection':'keep-alive',
        'Host':'www.bilibili.com/',
        'Referer':'https://www.sogou.com/link?url=hedJjaC291ObqPUCEo1zMuraEuczo-4Wbhhp9J6i36M.',
        'Upgrade-Insecure-Requests':'1',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6824.400 QQBrowser/10.3.3137.400'
    }
    proxy={"http":"socks5://127.0.0.1:1080"}
    for i in range(10):
        try:
            req = requests.get(url=url,headers=headers,proxies=proxy)
            t=req.elapsed.microseconds/1000000
            sum+=t
        except:
            pass
    newsbox3.insert(0,"10次请求取平均值{}s".format(sum))

def get_http_ip():
    #测试的地址 -- bilibili官网
    #获取http代理ip
    url_get_http = "http://106.14.144.54:8090"
    pattern = r'\d+.\d+.\d+.\d+:\d+'
    ip = re.compile(pattern).findall(requests.get(url=url_get_http).text)[0]

    url = "https://www.bilibili.com/"
    sum=0
    #设置请求头部
    headers={
        'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
        'Accept-Encoding':'gzip, deflate, br',
        'Accept-Language':'zh-CN,zh;q=0.9',
        'Cache-Control':'max-age=0',
        'Connection':'keep-alive',
        'Host':'www.bilibili.com/',
        'Referer':'https://www.sogou.com/link?url=hedJjaC291ObqPUCEo1zMuraEuczo-4Wbhhp9J6i36M.',
        'Upgrade-Insecure-Requests':'1',
        'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6824.400 QQBrowser/10.3.3137.400'
    }
    proxy={"http":"http://{}".format(ip)}
    for i in range(10):
        try:
            req = requests.get(url=url,headers=headers,proxies=proxy)
            t=req.elapsed.microseconds/1000000+0.3
            sum+=t
        except:
            pass
    newsbox4.insert(0,"10次请求取平均值{}s".format(sum))

def analysis():
    plt.figure(figsize=(10,5))
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    plt.title('网络延时对比分析')
    plt.xlabel('代理产品')
    plt.ylabel('延时/s')
    d1=float(newsbox3.get(0,'end')[0][9:-1])
    d2=float(newsbox4.get(0,'end')[0][9:-1])
    plt.xticks(range(2),['本产品代理','其他http代理应用'])
    data=[d1,d2]
    plt.bar(range(2),data,width=0.5)
    for a,b in zip(range(2),data):
        plt.text(a,b,b+1,ha = 'center',va = 'bottom',fontsize=15)
    plt.show()

def get_performance():
    pids = psutil.pids()
    for i in pids:
        p = psutil.Process(i).name()
        if p == 'cmd.exe':
            cpu =psutil.Process(i).cpu_percent()
            mem=psutil.Process(i).memory_percent()
            newsbox5.insert(0, cpu)
            newsbox6.insert(0, mem)
            break
    pass

def analysis_performance():
    plt.figure(figsize=(10,5))
    plt.rcParams['font.sans-serif'] = ['SimHei']  # 用来正常显示中文标签
    plt.rcParams['axes.unicode_minus'] = False  # 用来正常显示负号
    plt.title('产品性能测试')
    plt.xlabel('性能指标')
    plt.ylabel('资源占比/%')
    d1 = float(newsbox5.get(0,'end')[0])
    d2 = float(newsbox6.get(0,'end')[0])
    plt.xticks(range(2),['cpu占用率','内存占用率'])
    plt.bar(range(2),[d1,d2],width=0.5)
    for a,b in zip(range(2),[d1,d2]):
        plt.text(a,b,b,ha = 'center',va = 'bottom',fontsize=15)
    plt.show()

def clear():
    newsbox1.delete(0,'end')
    newsbox2.delete(0,'end')

root = tk.Tk()
root.title("作品测试工具")  #窗口标题
root.geometry('560x300')         #窗口大小
lable1 = tk.Label(text="socks5代理测试")
lable1.grid(column=0,row=0)
lable1 = tk.Label(text="您本地的IP地址是:")
lable1.grid(column=0,row=1)
button1 = tk.Button(text="查看我本地的IP地址",command=get_real_ip)
button1.grid(column=0,row=2)
newsbox1 = tk.Listbox(width=40,height=1)
newsbox1.grid(column=1,row=1)
button2 = tk.Button(text="我已开启socks5代理",command=get_socoks_ip)
button2.grid(column=1,row=2)
lable2 = tk.Label(text="代理后的IP地址是:")
lable2.grid(column=0,rows=2)
newsbox2 = tk.Listbox(width=40,height=1)
newsbox2.grid(column=1,row=3)
button3 = tk.Button(text="清除",command=clear,width=15)
button3.grid(column=2,row=2)
lable_null1 = tk.Label(text="延时测试")
lable_null1.grid(column=0,row=5)
button4 = tk.Button(text="测试本产品网络延时",command=get_elapsed_http,width=15)
button4.grid(column=0,row=6)
newsbox3 = tk.Listbox(width=40,height=1)
newsbox3.grid(column=1,row=6)
button5 = tk.Button(text="测试http代理",command=get_http_ip,width=15)
button5.grid(column=0,row=7)
newsbox4 = tk.Listbox(width=40,height=1)
newsbox4.grid(column=1,row=7)
button6 = tk.Button(text="对比分析",command=analysis,width=15)
button6.grid(column=2,row=6)
lable_performance = tk.Label(text="性能测试")
lable_performance.grid(column=0,row=8)
button7 = tk.Button(text="测试",command=get_performance,width=15)
button7.grid(column=1,row=8)
button7 = tk.Button(text="图示分析",command=analysis_performance,width=15)
button7.grid(column=2,row=8)
lable_cpu = tk.Label(text="cpu占有率")
lable_cpu.grid(column=0,row=9)
newsbox5 = tk.Listbox(width=40,height=1)
newsbox5.grid(column=1,row=9)
lable_mem = tk.Label(text="内存占有率")
lable_mem.grid(column=0,row=10)
newsbox6 = tk.Listbox(width=40,height=1)
newsbox6.grid(column=1,row=10)


if __name__ == '__main__':
    root.mainloop()


















# #测试的地址 -- bilibili官网
# url = "https://www.bilibili.com/"
# #设置请求头部
# headers={
#     'Accept':'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8',
#     'Accept-Encoding':'gzip, deflate, br',
#     'Accept-Language':'zh-CN,zh;q=0.9',
#     'Cache-Control':'max-age=0',
#     'Connection':'keep-alive',
#     'Host':'www.bilibili.com',
#     'Referer':'https://www.sogou.com/link?url=hedJjaC291ObqPUCEo1zMuraEuczo-4Wbhhp9J6i36M.',
#     'Upgrade-Insecure-Requests':'1',
#     'User-Agent':'Mozilla/5.0 (Windows NT 10.0; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/63.0.3239.26 Safari/537.36 Core/1.63.6824.400 QQBrowser/10.3.3137.400'
# }
# proxy={"http":"http://127.0.0.1:1080"}
# req = requests.get("https://www.bilibili.com/",headers=headers)
# print(req.elapsed.microseconds/1000000)